from django.db import models
from django.contrib.auth import get_user_model
from apps.product.models import SKU
from apps.address.models import Address

User = get_user_model()

class Order(models.Model):
    STATUS_CHOICES = (
        ('pending', '待支付'),
        ('paid', '已支付'),
        ('shipping', '配送中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    )

    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    order_number = models.CharField(max_length=32, unique=True, verbose_name='订单号')
    address = models.ForeignKey(Address, on_delete=models.PROTECT, verbose_name='收货地址')
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='订单总金额')
    remark = models.CharField(max_length=200, blank=True, verbose_name='备注')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='订单状态')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        ordering = ['-created_at']
        verbose_name = '订单'
        verbose_name_plural = '订单'

    def __str__(self):
        return f'订单号: {self.order_number}'

class OrderItem(models.Model):
    order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE, verbose_name='订单')
    sku = models.ForeignKey(SKU, on_delete=models.PROTECT, verbose_name='商品SKU')
    quantity = models.PositiveIntegerField(verbose_name='数量')
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='单价')
    amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='小计金额')

    class Meta:
        verbose_name = '订单项'
        verbose_name_plural = '订单项'

    def __str__(self):
        return f'{self.order.order_number} - {self.sku.name}' 